package com.dji.sample.wayline.service.impl;


import com.dji.sample.wayline.model.entity.WaylineFileEntity;
import com.dji.sample.wayline.model.entity.Waypoint;
import com.dji.sample.wayline.service.IWaylineFileService;
import com.dji.sample.wayline.service.IWaypointService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dji.sample.wayline.dao.IWaypointMapper;
import com.dji.sample.wayline.service.IOssFileService;
import com.dji.sample.wayline.util.KmzWaypointParser;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class WaylinepointServiceImpl implements IWaypointService {

    @Autowired
    private IWaylineFileService waylineFileService;

    @Autowired
    private IWaypointMapper waypointMapper;

    @Autowired
    private IOssFileService ossFileService;

    public List<Waypoint> getWaypointsByWaylineId(String waylineId){

        // 1) 先查数据库
        List<Waypoint> dbList = waypointMapper.selectList(
                new LambdaQueryWrapper<Waypoint>()
                        .eq(Waypoint::getWaylineId, waylineId)
                        .orderByAsc(Waypoint::getIndex)
        );
        if (dbList != null && !dbList.isEmpty()) {
            return dbList;
        }

        // 2) 查航线文件
        WaylineFileEntity entity = waylineFileService.getWaylineFileByWaylineId(waylineId);
        if (entity == null) {
            throw new RuntimeException("航线文件不存在: " + waylineId);
        }
        String objectKey = entity.getObjectKey();

        // 3) 通过OSS下载KMZ
        MultipartFile kmz = ossFileService.downloadFileByObjectKey(objectKey);

        // 4) 解析KMZ得到航点
        List<Waypoint> parsed = KmzWaypointParser.parseWaypoint(kmz);

        // 5) 绑定waylineId并入库
        for (Waypoint wp : parsed) {
            wp.setWaylineId(waylineId);
            waypointMapper.insert(wp);
        }

        // 6) 返回结果
        return parsed;
    }
}
